import React, { useState, useRef, useEffect, ReactText } from 'react';
import { Tree } from 'antd';
import { CaretDownOutlined, DownOutlined } from '@ant-design/icons';
import _remove from 'lodash/remove';
import classnames from 'classnames';
const { TreeNode, DirectoryTree } = Tree;
import './index.less';
// import isArray from 'lodash/isArray';
// import data from './data';
// import { buildingUtils, viewUtils } from '@/utils/arcgis';

const btnStyle = {
  width: 14,
};

type ITreeNode = {
  name: string;
  children?: ITreeNode[];
  key: string;
  [customProp: string]: any;
};

interface IBimTree {
  treeData: ITreeNode[];
  className?: string;
  viewBtn?: React.ReactNode;
  hideBtn?: React.ReactNode;
  loadData?: (treeNode: ITreeNode, indexTable: Dict) => Promise<any>;
  onViewClick?: (treeNode: ITreeNode, isView: boolean) => void;
  onConfigClick?: (treeNode: ITreeNode) => void;
  [customProp: string]: any;
}

type Dict = {
  [key: string]: any;
};

/**
 * 树形组件
 * 对antd的树包装了一下
 * 对样式进行微调 1目录树样式 2 工具条始终居右
 * 封装了一个节点index的速查表，提供给onload的第二个参数
 */
const BimTree: React.FC<IBimTree> = ({
  treeData,
  className,
  viewBtn,
  hideBtn,
  loadData = false,
  onViewClick,
  onConfigClick,
  ...restProps
}) => {
  // 内建index速查表
  const id2IndexTableRef = useRef<Dict>({});
  // 当前已经渲染的组件
  const [renderArr, setRenderArr] = useState<string[]>([]);
  // useEffect(() => {
  // id2IndexTableRef.current = {};
  // }, [treeData]);

  const handleExpandClick = expandedKeys => {
    console.log(expandedKeys);
  };
  console.log('treeData',treeData)
  // 查看点击
  const handleViewClick = async item => {
    const { name } = item;
    const isView = renderArr.indexOf(name) !== -1;
    if (typeof onViewClick !== 'function') return;
    await onViewClick(item, isView);
    if (renderArr.indexOf(name) !== -1) {
      setRenderArr(arr => _remove(arr, s => s !== name));
    } else {
      setRenderArr(arr => [...arr, name]);
    }
  };

  const handleConfigClick = item => {
    if (typeof onConfigClick !== 'function') return;
    onConfigClick(item);
  };

  const onLoadData = async (treeNode): Promise<any> => {
    const { key } = treeNode;
    if (typeof loadData !== 'function') {
      return Promise.resolve();
    }
    return loadData(treeNode, id2IndexTableRef.current[key]);
  };

  const viewEle = viewBtn || <img src={require('./images/hide.png')} alt="" style={btnStyle} />;
  const hideEle = hideBtn || <img src={require('./images/show.png')} alt="" style={btnStyle} />;

  const renderTreeNodes = (
    data = {},
    pNode: any = null,
    level: number = 1,
    indexArr: ReactText[] = [],
  ) => {
    return Object.keys(data).map((key, index) => {
      let item = data[key];
      const _indexArr = [...indexArr, index];
      if (!id2IndexTableRef.current[item.key]) {
        id2IndexTableRef.current[item.key] = _indexArr;
      }
      const title = (
        <span>
          {item.name}
          <span onClick={e => e.stopPropagation()} className={'operate-bar'}>
            <span
              onClick={() => handleViewClick(item)}
              className={classnames('operate-bar-btn', 'operate-bar-btn-view', {})}
            >
              {renderArr.length && renderArr.indexOf(item.name) !== -1 ? viewEle : hideEle}
            </span>
            <span
              onClick={() => {
                handleConfigClick(item);
              }}
              className={classnames('operate-bar-btn', 'operate-bar-btn-config', {})}
            >
              <img src={require('./images/config.png')} alt="" style={btnStyle} />
            </span>
            <span className={classnames('operate-bar-btn', 'operate-bar-btn-setting', {})}>
              <img src={require('./images/setting.png')} alt="" style={btnStyle} />
            </span>
          </span>
        </span>
      );

      if (item.children && item.children.length) {
        return (
          <TreeNode
            title={title}
            key={`${item.key}`}
            // @ts-ignore
            _name={item.name}
            _level={level}
            _parent={pNode}
          >
            {renderTreeNodes(item.children, item, level + 1, _indexArr)}
          </TreeNode>
        );
      }

      return (
        <TreeNode
          key={`${item.key}`}
          title={title}
          // @ts-ignore
          _name={item.name}
          _level={level}
          _parent={pNode}
        />
      );
    });
  };

  return (
    <div className={classnames('geomap-widget_bim-tree', className)}>
      <DirectoryTree
        icon={null}
        // onSelect={onTreeSelect}
        // defaultExpandAll
        expandAction={'doubleClick'}
        onExpand={handleExpandClick}
        loadData={onLoadData}
        switcherIcon={<CaretDownOutlined className={'geomap-widget_bim-tree-switcher-icon'} />}
        {...restProps}
      >
        {renderTreeNodes(treeData)}
      </DirectoryTree>
    </div>
  );
};

export default BimTree;
